
<style lang="less">
@import './table.less';
</style>
<style>
.toolBar {
  margin-bottom: 10px;
}

.ivu-dropdown {
  margin: 0px;
}

.tCheck {
  padding-left: 10px;
  float: left;
  clear: left;
  z-index: 9999;
}
</style>

<template>
<Row>
  <Row class="toolBar" justify="space-between">
    <Col span="8">
    <Button-group>
      <Tooltip v-if="read" content="查看详细" placement="bottom-start" transfer>
        <Button type="ghost" @click="get()">
           查看
          </Button>
      </Tooltip>
      <Tooltip v-if="addition" content="申请补充送检" placement="bottom-start" transfer>
        <Button type="ghost" @click="additionClick()">
           申请补充送检
          </Button>
      </Tooltip>
      <Tooltip v-if="padd" content="添加" placement="bottom-start" transfer>
        <Button type="ghost" @click="addClick()">
            添加
          </Button>
      </Tooltip>
      <Tooltip v-if="editCheck" content="编辑所选" placement="bottom-start" transfer>
        <Button type="ghost" @click="editCheckClick()">
            编辑
          </Button>
      </Tooltip>
      <Tooltip v-if="delCheck" content="删除所选" placement="bottom-start" transfer>
        <Button type="ghost" @click="delCheckClick()">
            删除
          </Button>
      </Tooltip>
      <Tooltip v-if="assign" content="分配资源" placement="bottom-start" transfer>
        <Button type="ghost" @click="assignClick()">
           分配资源
          </Button>
      </Tooltip>
      <Tooltip v-if="reset" content="重置密码" placement="bottom-start" transfer>
        <Button type="ghost" @click="resetClick()">
           重置密码
          </Button>
      </Tooltip>
      <Tooltip v-if="flowStatus" content="查看流程" placement="bottom-start" transfer>
        <Button type="ghost" @click="getflow()">
            查看流程
          </Button>
      </Tooltip>
      <Tooltip v-if="flowstart" content="上报" placement="bottom-start" transfer>
        <Button type="ghost" @click="FlowStartClick()">
            上报
          </Button>
      </Tooltip>
      <Tooltip v-if="approve" content="审批" placement="bottom-start" transfer>
        <Button type="ghost" @click="approveClick()">
           审批
          </Button>
      </Tooltip>
      <Tooltip v-if="order" content="生成订单" placement="bottom-start" transfer>
        <Button type="ghost" @click="setOrder()">
            生成订单
          </Button>
      </Tooltip>
    </Button-group>
    </Col>
    <Col span="16">
    <Button-group style="float: right;">
      <Tooltip content="刷新" placement="bottom-start" transfer>
        <Button type="ghost" @click="refresh">
            刷新
          </Button>
      </Tooltip>
      <Tooltip content="导出全部数据" placement="bottom-start" transfer>
        <Button type="ghost" @click="exportData(1)">
           导出全部
          </Button>
      </Tooltip>
      <Tooltip content="导出当前页数据" placement="bottom-start" transfer>
        <Button type="ghost" @click="exportData(2)">
           导出当前
          </Button>
      </Tooltip>
    </Button-group>
    <Input v-model="searchKey" icon="ios-search-strong" placeholder="请输入..." style="width:200px;float:right;">
    </Input>
    </Col>
  </Row>
  <Table :context="self" border stripe disabled-hover :columns="columnsList" :data="curTableData" :loading="loading" ref="table" @on-selection-change="selectRow" @on-select="handelSelect" @on-row-dblclick="show">
  </Table>
  <div style="margin: 10px;overflow: hidden">
    <div style="float: right;">
      <Page :total="total" :current="current" :pageSize="pageSize" :page-size-opts="pageSizeOpts" @on-change="changePage" @on-page-size-change="changeSize" show-elevator show-total show-sizer></Page>
    </div>
  </div>
  <Modal v-show="dataShow" title="查看数据详细信息" v-model="showData" class="editm">
    <Form ref="showForm" :model="showItem" :label-width="80">
      <Form-item v-for="(val, key)  in showItem" :label="key" :key="key">
        <Input :value="val" disabled :icon="key==='Logo'? val:''"></Input>
      </Form-item>
    </Form>
  </Modal>

</Row>
</template>

<script>
import api from '@/api'

const editButton = (vm, h, currentRow, index) => {
  return h('Button', {
    props: {
      type: currentRow.editting ? 'success' : 'primary',
      loading: currentRow.saving
    },
    style: {
      margin: '0 5px'
    },
    on: {
      'click': () => {
        if (!currentRow.editting) {
          if (currentRow.edittingCell) {
            for (let name in currentRow.edittingCell) {
              currentRow.edittingCell[name] = false;
              vm.edittingStore[index].edittingCell[name] = false;
            }
          }
          vm.edittingStore[index].editting = true;
          vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
        } else {
          vm.edittingStore[index].saving = true;
          vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
          let edittingRow = vm.edittingStore[index];
          edittingRow.editting = false;
          edittingRow.saving = false;
          vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
          vm.$emit('input', vm.handleBackdata(vm.thisTableData));
          vm.$emit('on-change', vm.handleBackdata(vm.thisTableData), index);
        }
      }
    }
  }, currentRow.editting ? '保存' : '编辑');
};
const deleteButton = (vm, h, currentRow, index) => {
  return h('Poptip', {
    props: {
      confirm: true,
      title: '您确定要删除这条数据吗?',
      transfer: true
    },
    on: {
      'on-ok': () => {
        vm.thisTableData.splice(index, 1);
        vm.$emit('input', vm.handleBackdata(vm.thisTableData));
        vm.$emit('on-delete', vm.handleBackdata(vm.thisTableData), index);
      }
    }
  }, [
    h('Button', {
      style: {
        margin: '0 5px'
      },
      props: {
        type: 'error',
        placement: 'top'
      }
    }, '删除')
  ]);
};
const incellEditBtn = (vm, h, param) => {
  if (vm.hoverShow) {
    return h('div', {
      'class': {
        'show-edit-btn': vm.hoverShow
      }
    }, [
      h('Button', {
        props: {
          type: 'text',
          icon: 'edit'
        },
        on: {
          click: (event) => {
            vm.edittingStore[param.index].edittingCell[param.column.key] = true;
            vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
          }
        }
      })
    ]);
  } else {
    return h('Button', {
      props: {
        type: 'text',
        icon: 'edit'
      },
      on: {
        click: (event) => {
          vm.edittingStore[param.index].edittingCell[param.column.key] = true;
          vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
        }
      }
    });
  }
};
const saveIncellEditBtn = (vm, h, param) => {
  return h('Button', {
    props: {
      type: 'text',
      icon: 'checkmark'
    },
    on: {
      click: (event) => {
        vm.edittingStore[param.index].edittingCell[param.column.key] = false;
        vm.thisTableData = JSON.parse(JSON.stringify(vm.edittingStore));
        vm.$emit('input', vm.handleBackdata(vm.thisTableData));
        vm.$emit('on-cell-change', vm.handleBackdata(vm.thisTableData), param.index, param.column.key)
      }
    }
  });
};
const cellInput = (vm, h, param, item) => {
  return h('Input', {
    props: {
      type: 'text',
      value: vm.edittingStore[param.index][item.key]
    },
    on: {
      'on-change' (event) {
        let key = item.key;
        vm.edittingStore[param.index][key] = event.target.value;
      }
    }
  });
};

export default {
  data() {
    return {
      self: this,
      total: 0,
      current: 1,
      pageSize: this.pageS,
      searchKey: '',
      spinShow: false,
      showData: false,
      showItem: {},
      pageSizeOpts: [10, 20, 50, 100],
      selectRows: [], //选择的数据
      columns: [],
      thisTableData: [],
      edittingStore: []
    }
  },
  props: {
    loading: false,
    pageS: {
      type: Number,
      default: 10
    },
    columnsList: Array,
    value: Array,
    url: String,
    busyName: String,
    busyTable: String,
    editIncell: {
      type: Boolean,
      default: false
    },
    hoverShow: {
      type: Boolean,
      default: false
    },
    dataShow: {
      type: Boolean,
      default: false
    },
    read: {
      type: Boolean,
      default: false
    },
    add: {
      type: Boolean,
      default: false
    },
    delCheck: {
      type: Boolean,
      default: false
    },
    editCheck: {
      type: Boolean,
      default: false
    },
    assign: {
      type: Boolean,
      default: false
    },
    reset: {
      type: Boolean,
      default: false
    },
    check: {
      type: Boolean,
      default: false
    },
    op: {
      type: Boolean,
      default: false
    },
    inst: {
      type: Boolean,
      default: false
    },
    flowstart: {
      type: Boolean,
      default: false
    },
    flowStatus: {
      type: Boolean,
      default: false
    },
    approve: {
      type: Boolean,
      default: false
    },
    order: {
      type: Boolean,
      default: false
    },
    addition: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    state() {
      return this.$store.state.app
    },
    padd() {
      let ret = false
      // console.log("this.add", this.add)
      if (this.add) {
        let data = this.state.router.currentPageName + "-增加"
        // console.log("this.state.router.currentPageName", data)
        for (var e in this.state.menu) {
          if (data === this.state.menu[e].Name) {
            // console.debug(this.state.menu[e].Name)
            ret = true
            break
            // return true
          }
        }
      }
      return ret
    },
    //        过滤数据表
    filiterTableDate() {
      let fdata
      if (!this.thisTableData) {
        fdata = []
      } else {
        let e = this.thisTableData.slice()
        let keys = this.searchKey
        let filterData = function(element) {
          if (keys === "") {
            return true
          }
          for (let o in element) {
            if (String(element[o]).indexOf(keys) >= 0) {
              return true
            }
          }
          return false
        }
        fdata = e.filter(filterData)
        this.total = fdata.length
        if (this.thisTableData.length < 1) {
          fdata = this.thisTableData
        }
      }
      return fdata
    },
    //      当前表数据
    curTableData() {
      // console.log(this.columns)
      if (!this.filiterTableDate) {
        return []
      }
      let from = this.pageSize * (this.current - 1)
      let to = from + this.pageSize
      return this.filiterTableDate.slice(from, to)
    },
  },
  watch: {
    value(data) {
      this.init();
    }
  },
  methods: {
    init() {
      let vm = this;
      let editableCell = this.columnsList.filter(item => {
        if (item.editable) {
          if (item.editable === true) {
            return item;
          }
        }
      });
      let cloneData = []
      if (this.value) {
        cloneData = JSON.parse(JSON.stringify(this.value))
      }
      let res = [];
      res = cloneData.map((item, index) => {
        let isEditting = false;
        if (this.thisTableData[index]) {
          if (this.thisTableData[index].editting) {
            isEditting = true;
          } else {
            for (const cell in this.thisTableData[index].edittingCell) {
              if (this.thisTableData[index].edittingCell[cell] === true) {
                isEditting = true;
              }
            }
          }
        }
        if (isEditting) {
          return this.thisTableData[index];
        } else {
          this.$set(item, 'editting', false);
          let edittingCell = {};
          editableCell.forEach(item => {
            edittingCell[item.key] = false;
          });
          this.$set(item, 'edittingCell', edittingCell);
          return item;
        }
      });
      // console.log(this.columnsList)
      this.thisTableData = res;
      this.edittingStore = JSON.parse(JSON.stringify(this.thisTableData));
      this.columnsList.forEach(item => {
        if (item.editable) {
          // console.log(item)
          item.render = (h, param) => {
            let currentRow = this.thisTableData[param.index];
            // console.log(currentRow)
            if (!currentRow.editting) {
              if (this.editIncell) {
                // console.log(currentRow)
                return h('Row', {
                  props: {
                    type: 'flex',
                    align: 'middle',
                    justify: 'center'
                  }
                }, [
                  h('Col', {
                    props: {
                      span: '22'
                    }
                  }, [!currentRow.edittingCell[param.column.key] ? h('span', currentRow[item.key]) : cellInput(this, h, param, item)]),
                  h('Col', {
                    props: {
                      span: '2'
                    }
                  }, [
                    currentRow.edittingCell[param.column.key] ? saveIncellEditBtn(this, h, param) : incellEditBtn(this, h, param)
                  ])
                ]);
              } else {
                return h('span', currentRow[item.key]);
              }
            } else {
              return h('Input', {
                props: {
                  type: 'text',
                  value: currentRow[item.key]
                },
                on: {
                  'on-change' (event) {
                    let key = param.column.key;
                    vm.edittingStore[param.index][key] = event.target.value;
                  }
                }
              });
            }
          };
        }
        if (item.handle) {
          item.render = (h, param) => {
            let currentRowData = this.thisTableData[param.index];
            if (item.handle.length === 2) {
              return h('div', [
                editButton(this, h, currentRowData, param.index),
                deleteButton(this, h, currentRowData, param.index)
              ]);
            } else if (item.handle.length === 1) {
              if (item.handle[0] === 'edit') {
                return h('div', [
                  editButton(this, h, currentRowData, param.index)
                ]);
              } else {
                return h('div', [
                  deleteButton(this, h, currentRowData, param.index)
                ]);
              }
            }
          };
        }
      });
    },
    handleBackdata(data) {
      let clonedData = JSON.parse(JSON.stringify(data));
      clonedData.forEach(item => {
        delete item.editting;
        delete item.edittingCell;
        delete item.saving;
      });
      return clonedData;
    },
    //        刷新数据
    refresh() {
      this.$emit('refresh')

    },
    //        选择数据
    selectRow(selection) {
      this.selectRows = selection
    },
    //      改变页码大小
    changeSize(current) {
      this.pageSize = current
    },
    //      改变页码
    changePage(current) {
      // 这里直接更改了模拟的数据，真实使用场景应该从服务端获取数据
      this.current = current
    },
    //      导出数据1为原始数据，2为当前数据
    exportData(type) {
      if (type === 1) {
        this.$refs.table.exportCsv({
          filename: '原始数据',
          quoted:true
          //            columns: this.columns.filter((col, index) => index < 5),
          //            data: this.thisTableData,
        });
      } else if (type === 2) {
        this.$refs.table.exportCsv({
          filename: '排序和过滤后的数据',
          original: false,
          quoted:true
        });
      }
    },
    //      显示详细记录
    show(row) {
      // if (this.dataShow) {
      //   this.showItem = row
      //   this.showData = true
      // }
    },
    //     查看
    get(row) {
       if (!this.selectRows || this.selectRows.length != 1) {
        this.$Message.warning('必须选择一个需要查看的项目！');
      } else {
        this.$emit('get',  this.selectRows[0])
      }
      
    },
    //      编辑表格数据
    edit(index) {
      // console.log(this.curTableData[index])
      this.$emit('edit', this.curTableData[index])
    },
    editCheckClick() {
      if (!this.selectRows || this.selectRows.length !== 1) {
        this.$Message.error("编辑数据必须选择一个数据！", 4)
      } else {
        this.$emit('edit', this.selectRows[0])
      }
    },
    //      编辑表格数据
    getflow(index) {
      // console.log(this.curTableData[index])
      this.$router.push({
        name: '流程实例',
        params: {
          id: this.selectRows[0].Id
        }
      })
    },
    //      新增
    addClick() {
      this.$emit('add')
    },
    additionClick() {
      if (!this.selectRows || this.selectRows.length != 1) {
        this.$Message.warning('必须选择一个需要申请的项目！');
      } else {
        this.$emit('addition', this.selectRows[0])
      }
    },
    //      授权
    assignClick() {
      // let list = []
      // for (let i = 0; i < this.selectRows.length; i++) {
      //   list.push(this.selectRows[i])
      // }
      this.$emit('assign', this.selectRows)
    },
    //      重置
    resetClick() {
      let list = []
      for (let i = 0; i < this.selectRows.length; i++) {
        list.push(this.selectRows[i].Id)
      }
      this.$emit('reset', list)
    },
    //  流程开始
    FlowStartClick() {
      this.$Modal.confirm({
        title: '流程开始',
        content: '<p>请确认所选数据填报完整,开始进入审批流程</p>' +
          '<p>是否继续？</p>',
        onOk: () => {
          let list = []
          for (let i = 0; i < this.selectRows.length; i++) {
            let flowins=this.selectRows[i]
            flowins.busyName=this.busyName
            flowins.busyTable=this.busyTable
            list.push(flowins)
          }
          this.FlowStartApi(list)
        },
        onCancel: () => {}
      })

    },
    FlowStartApi(data) {
      this.$api.FlowStart(data).then(res => {
        if (!res.error) {
          this.refresh()
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      })
    },
    //   审批  
    approveClick() {
      if (!this.selectRows || this.selectRows.length != 1) {
        this.$Message.warning('必须选择一个需要审批的项目！');
      } else {
        this.$emit('approveClick', this.selectRows[0])
      }
    },
    // 生成订单
    setOrder() {
      if (this.selectRows.length !== 1) {
        this.$Message.error("生成订单必须选择一个数据进行授权！", 4)
      } else {
        this.$emit('setOrder', this.selectRows[0])
      }
    },
    //      删除所选确认
    delCheckClick() {
      if (!this.selectRows || this.selectRows.length < 1) {
        this.$Message.warning('必须选择一个需要删除的项目！');
      } else {
        this.$Modal.confirm({
          title: '删除确认',
          content: '<p>请确认此数据删除后，不影响其他功能或人员使用。</p>' +
            '<p>是否继续删除？</p>',
          onOk: () => {
            this.delList(this.selectRows)
          },
          onCancel: () => {}
        })
      }
    },
    //      删除所选
    delList(rows) {
      let list = []
      for (let i = 0; i < rows.length; i++) {
        list.push(rows[i].Id)
      }
      this.$emit('delList', list)
    },
    //      删除确认
    remove(index) {
      this.$Modal.confirm({
        title: '删除确认',
        content: '<p>请确认此数据删除后，不影响其他功能或人员使用。</p>' +
          '<p>是否继续删除？</p>',
        onOk: () => {
          this.delete(index)
        },
        onCancel: () => {}
      })
    },
    //      删除
    delete(index) {
      let id = this.curTableData[index].Id
      this.$emit('del', this.curTableData[index])
    },
    handelSelect(selection) {
      this.$emit('handelSelect', selection)
    }
  },
  created() {
    this.init();
  },
  mounted() {
    //修改删除操作按钮
    if (this.op) {
      let op = {
        title: '操作',
        key: 'action',
        width: 150,
        align: 'center',
        render: (h, params) => {
          return h('div', [
            h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              },
              on: {
                click: () => {
                  this.edit(params.index)
                }
              }
            }, '修改'),
            h('Button', {
              props: {
                type: 'error',
                size: 'small'
              },
              on: {
                click: () => {
                  this.remove(params.index)
                }
              }
            }, '删除')
          ]);
        }
      }
      this.columns.push(op)
    }
    if (this.inst) {
      let inst = {
        title: '操作',
        key: 'action',
        width: 150,
        align: 'center',
        render: (h, params) => {
          return h('div', [
            h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              style: {
                marginRight: '5px'
              },
              on: {
                click: () => {
                  this.edit(params.index)
                }
              }
            }, '详情'),
            h('Button', {
              props: {
                type: 'error',
                size: 'small'
              },
              on: {
                click: () => {
                  this.getflow(params.index)
                }
              }
            }, '流程')
          ]);
        }
      }
      this.columns.push(inst)
    }
    //多选框
    if (this.check) {
      let ck = {
        type: 'selection',
        width: 60,
        align: 'center'
      }
      this.columnsList.unshift(ck)
    }

    //      this.getall()
  }
}
</script>


